package top.hkyzf.study.leetcode.string;

import org.junit.Test;

import java.util.regex.Pattern;

/**
 * @author 朱峰
 * @date 2022-1-27 8:33
 */
public class 句子中的有效单词数_2047 {
    public int countValidWords(String sentence) {
        if (sentence == null || sentence.length() < 1) {
            return -1;
        }
        String[] strings = sentence.split(" ");
        int result = 0;
        for (String word : strings) {
            if (isValid(word)) {
                result++;
            }
        }
        return result;
    }

    boolean isValid (String word) {
        int num = 0;
        if (word.length() == 0) {
            return false;
        }
        for (int i = 0; i < word.length(); i++) {
            // 含有数字直接返回 false
            if (word.charAt(i) >= '0' && word.charAt(i) <= '9') {
                return false;
            }
            // 含有标点并且不是最后一位
            if ((word.charAt(i) == '!' || word.charAt(i) == '.' || word.charAt(i) == ',') && i != word.length()-1) {
                return false;
            }
            // 含有 - 并且在单词首尾
            if (word.charAt(i) == '-' && (i == 0 || i == word.length()-1)) {
                return false;
            }
            // 含有 - 并且前面是 !.,-
            /*if (word.charAt(i) == '-' && (word.charAt(i-1) == '!' || word.charAt(i-1) == '.' || word.charAt(i-1) == ',' || word.charAt(i-1) == '-')) {
                return false;
            }*/
            // 含有 - 并且后面是 !.,-
            if (word.charAt(i) == '-' && (word.charAt(i+1) == '!' || word.charAt(i+1) == '.' || word.charAt(i+1) == ',' || word.charAt(i+1) == '-')) {
                return false;
            }
            // 最多一个 - 存在
            if (word.charAt(i) == '-') {
                num++;
            }
        }
        return num <= 1;
    }

    public int countValidWordsByRegex(String sentence) {
        if (sentence == null || sentence.length() < 1) {
            return -1;
        }
        String[] strings = sentence.split(" ");
        int result = 0;
        for (String word : strings) {
            if (word.length() < 1) {
                continue;
            }
            String patten = "[a-z]+-?[a-z]+[!.,]?|[a-z]*[!.,]?";
            if (Pattern.matches(patten, word)) {
                result++;
            }
        }
        return result;
    }

    @Test
    public void testCountValidWords () {
        String sentence = ". ! 7hk al6 l! aon49esj35la k3 7u2tkh 7i9y5 !jyylhppd et v- h!ogsouv 5";
        System.out.println(countValidWordsByRegex(sentence));
    }
}
